package com.example.adminsystem.config;

import com.example.adminsystem.common.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import com.example.adminsystem.filter.JwtAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");  // 添加字符编码设置
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(
                    new ObjectMapper().writeValueAsString(
                            ResponseResult.error("请先登录系统")
                    )
            );
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    @Lazy
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 关闭 CSRF 保护
            .csrf().disable()
            .authorizeRequests()
                // 放行登录接口和Swagger文档
                .antMatchers("/auth","/auth/**", "/swagger-ui.html", "/swagger-ui/**",
                           "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**").permitAll()
                // 其他请求需要认证
                .anyRequest().authenticated()
            .and()
            // 禁用HTTP Basic认证
            .httpBasic().disable()
            // 添加JWT过滤器
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        http.exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint());
            
        return http.build();
    }
}
